import connector.datebasedriver
from connector.datebasedriver import datebasedriver

class userdao:
    # 注册用户，需要用户名、用户密码、用户角色
    def register_user(driver: datebasedriver, username: str, password: str, role: int):
        result: tuple = driver.select_one(
            'select user_id from user where user_name = "{}"'.format(username), log=True)
        if result is None:
            update: int = driver.insert(
                'insert into user(user_name, user_password, user_role) values ("{}","{}",'
                '{})'.format(username, password, role), log=True)
        else:
            return 0
        return update


    def get_users(driver: datebasedriver) -> tuple:
        result: tuple = driver.select_all("select * from user")
        return result


    def update_user(driver: datebasedriver, user_id: int, username: str, password: str, role: int):
        result: int = driver.update(
            'update user set user_name="{}", user_password="{}",user_role={} where '
            'user_id={}'.format(username, password, role, user_id))
        return result


    # # 重置密码
    # def rest_password(driver: DatabaseDriver, user_id: int, new_password:str):
    #     # 更新用户
    #     result: int = driver.update(
    #         'update user set user_password="{}" where user_id="{}"'.format(new_password, user_id))
    #     return result


    # 根据用户id获取用户
    def get_user_by_id(driver: datebasedriver, user_id: int) -> tuple:
        result: tuple = driver.select_one(sql="select * from user where user_id={}".format(user_id))
        return result


    def get_user_by_username(self, driver: datebasedriver, username: str) -> tuple:
        return driver.select_one(sql='select * from user where user_name="{}"'.format(username))


    def get_username_by_user_id(driver: datebasedriver, user_id: int):
        return driver.select_one('select user_name from user where user_id="{}"'.format(user_id))

    def update_user_password(self, driver: datebasedriver, user_id: int, new_password: str):
        driver.update(sql='update user set user_password="{}" where user_id={}'.format(new_password, user_id))


    # 根据用户名密码获取用户，登录的时候需要
    def get_user_by_username_and_password(driver: datebasedriver, username, password):
        return driver.select_one(sql='select * from user where user_name="{}" and user_password="{}"'.format(username, password))


    if __name__ == "__main__":
        driver = connector.datebasedriver.datebasedriver()
        print(get_user_by_id)
        driver.close()
def login(driver: datebasedriver, username: str, password: str) -> tuple:
    result: tuple = driver.select_one(
        'select user_id, user_role from user where user_name = "{}" and '
        'user_password = "{}"'.format(username, password), log=True)
    return result